package com.itheima.appserver.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.appserver.config.HuanXinConfig;
import com.itheima.appserver.config.MyThreadLocal;
import com.itheima.appserver.excepiton.ErrInfo;
import com.itheima.appserver.excepiton.ErroResult;
import com.itheima.appserver.excepiton.MyEx;
import com.itheima.commons.pojo.Announcement;
import com.itheima.commons.pojo.Comment;
import com.itheima.commons.pojo.UserInfo;
import com.itheima.commons.pojo.Users;
import com.itheima.commons.vo.*;
import com.itheima.dubbo.interfaces.AnnouncementApi;
import com.itheima.dubbo.interfaces.CommentApi;
import com.itheima.dubbo.interfaces.UserInfoApi;
import com.itheima.dubbo.interfaces.UsersApi;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @项目名称: tanhua-53
 * @包名: com.itheima.appserver.service
 * @作者: 李云飞
 * @日期: 2021-12-09
 */
@Service
public class IMService {

    @Autowired
    private MyCenterService myCenterService;

    @Reference
    private UsersApi usersApi;

    @Autowired
    private HuanXinConfig hxconfig;

    @Autowired
    private RequestService requestService;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private AnnouncementApi announcementApi;


    @Reference
    private CommentApi commentApi;

    public UserInfoVo queryUserInfoByUserName(String userName) {
        return myCenterService.queryUserInfoByUserId(Convert.toLong(StrUtil.subAfter(userName, "_", true)));
    }

    // 添加好友
    public void contactUser(Long friendId) {
        // 先往好友表中添加两条记录
        Users users = new Users();
        users.setId(new ObjectId());
        users.setUserId(MyThreadLocal.getUserId());
        users.setFriendId(friendId);
        users.setDate(System.currentTimeMillis());
        usersApi.addUsers(users);

        Users users2 = new Users();
        users2.setId(new ObjectId());
        users2.setUserId(friendId);
        users2.setFriendId(MyThreadLocal.getUserId());
        users2.setDate(System.currentTimeMillis());
        usersApi.addUsers(users2);

        // 给环信发送消息 让环信把两人绑定为好友
        // /{org_name}/{app_name}/users/{owner_username}/contacts/users/{friend_username}
        HttpResponse response = requestService.execute(hxconfig.getUrl() + hxconfig.getOrgName()
                + "/" + hxconfig.getAppName() + "/users/" + "HX_" + MyThreadLocal.getUserId()
                + "/contacts/users/HX_" + friendId, null, Method.POST);
        if (!response.isOk()) {
            throw new MyEx(ErroResult.fail(ErrInfo.addFriendError));
        }
    }

    /**
     * 查询好友列表
     *
     * @param page     分页页码
     * @param pageSize 页面条数
     * @param keyword  关键词的搜索  如果关键词不为空 我们要查询全部好友并且根据关键词过滤  如果没有关键词 我们做分页
     * @return
     */
    public PageResult queryContactsList(Integer page, Integer pageSize, String keyword) {
        // 所有好友列表
        List<Users> users = usersApi.findUsersByUserId(MyThreadLocal.getUserId(), page, pageSize, keyword);
        // 提取好友的id
        List<Long> friendIds = CollUtil.getFieldValues(users, "friendId", Long.class);
        // 查询UserInfo
        Map<Long, UserInfo> userInfoListByUserIds = userInfoApi.findUserInfoByUserid(UserInfo.builder().nickName(keyword).build(), friendIds);
        // 开始拼凑VO对象
        List<UsersVo> vos = new ArrayList<>();
        for (UserInfo info : userInfoListByUserIds.values()) {
            UsersVo usersVo = new UsersVo();
            // 用户ID
            usersVo.setId(info.getUserId());
            // 环信ID
            usersVo.setUserId("HX_" + info.getUserId());
            usersVo.setAvatar(info.getLogo());
            usersVo.setNickname(info.getNickName());
            usersVo.setGender(info.getSex() == 1 ? "man" : "woman");
            usersVo.setAge(info.getAge());
            usersVo.setCity(StrUtil.subBefore(info.getCity(), "-", false));
            vos.add(usersVo);
        }

        return new PageResult(page, pageSize, 0L, vos);
    }

    /**
     * 查询谁评论了我的列表
     *
     * @param page
     * @param pageSize
     * @param commentType 1 点赞  2 评论  3 喜欢
     * @return
     */
    public PageResult queryCommentList(Integer page, Integer pageSize, int commentType) {

        // 查询点赞/评论/喜欢列表
        List<Comment> commentList = commentApi.queryCommentListByUserId(page, pageSize, MyThreadLocal.getUserId(), commentType);
        // 从这个列表中提取发布评论的人的id
        List<Long> userIds = CollUtil.getFieldValues(commentList, "userId", Long.class);
        // 查询发布评论的人的信息
        Map<Long, UserInfo> infoMap = userInfoApi.findUserInfoByUserid(null, userIds);
        // 拼凑VO对象
        List<MessageCommentVo> voList = new ArrayList<>();
        for (Comment comment : commentList) {
            MessageCommentVo vo = new MessageCommentVo();
            UserInfo info = infoMap.get(comment.getUserId());
            vo.setId(info.getUserId().toString());
            vo.setAvatar(info.getLogo());
            vo.setNickname(info.getNickName());
            vo.setCreateDate(DateUtil.format(new Date(comment.getCreated()), "yyyy-MM-dd HH:mm"));
            voList.add(vo);
        }

        return new PageResult(page, pageSize, 0L, voList);
    }

    /**
     * 查询系统公告列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryMessageAnnouncementList(Integer page, Integer pageSize) {
        List<Announcement> announcementList = announcementApi.findAnnouncementByPage(page, pageSize);
        List<AnnouncementVo> announcementVoList = new ArrayList<>();
        for (Announcement announcement : announcementList) {
            AnnouncementVo vo = new AnnouncementVo();
            vo.setId(announcement.getId().toString());
            vo.setTitle(announcement.getTitle());
            vo.setDescription(announcement.getDescription());
            vo.setCreateDate(DateUtil.format(announcement.getCreated(), "yyyy-MM-dd HH:mm"));
            announcementVoList.add(vo);
        }
        return new PageResult(page, pageSize, 0L, announcementVoList);
    }
}